<%@ page import="com.github.pagehelper.PageInfo" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
    String basePath = request.getScheme() + "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
%>
<html>
<head>
    <title>员工列表</title>
    <base href="<%=basePath%>" />
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"
            integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
            crossorigin="anonymous"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
            integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
            crossorigin="anonymous"></script>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

</head>
<body>

<%--员工添加模态框--%>
<div class="modal fade" id="empAddModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" name="empName" class="form-control" id="empName_add_input" placeholder="empName">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" name="email" class="form-control" id="email_add_input" placeholder="email@atguigu.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_add_input" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-10">
                            <select class="form-control" name="dId" id="dept_add_select">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>
<%--员工修改模态框--%>
<div class="modal fade" id="empUpdateModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="empName_update_static"></p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" name="email" class="form-control" id="email_update_input" placeholder="email@atguigu.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_update_input" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_update_input" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-10">
                            <select class="form-control" name="dId" id="dept_update_select">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
            </div>
        </div>
    </div>
</div>
<div class="container">
    <%--标题--%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSM_CRUD</h1>
        </div>
    </div>
    <%--按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button type="button" class="btn btn-success" id="emp_add_model_btn">新增</button>
            <button type="button" class="btn btn-danger" id="emp_del_all_btn">删除</button>
        </div>
    </div>
    <%--显示表格数据--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_tables">
                <thead>
                    <tr>
                        <th>
                            <input type="checkbox" id="check_all"/>
                        </th>
                        <th>#</th>
                        <th>empName</th>
                        <th>gender</th>
                        <th>email</th>
                        <th>deptName</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
    <%--显示分页信息--%>
    <div class="row">
        <div class="col-md-6" id="page_info_area">
        </div>
        <%--显示页码导航条--%>
        <div class="col-md-6" id="page_nav_area">
        </div>
    </div>
</div>
<script type="text/javascript">
    var totalRecord;
    var currentPage;
    $(function () {
        to_page(1)
    });
    
    function build_emps_table(data) {
        $("#emps_tables tbody").empty();
        var emps = data.extend.pageInfo.list;
        $.each(emps, function (index, emp) {
            var checkBoxId = $("<td><input type='checkbox' class='check_item'/></td>");
            var empIdTd = $("<td></td>").append(emp.empId);
            var empNameTd = $("<td></td>").append(emp.empName);
            var genderTd = $("<td></td>").append(emp.gender);
            var emailTd = $("<td></td>").append(emp.email);
            var deptNameTd = $("<td></td>").append(emp.department.deptName);

            var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");
            editBtn.attr("edit-id",emp.empId);
            var deleteBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
            deleteBtn.attr("delete-id",emp.empId);
            var btnTd = $("<td></td>").append(editBtn).append(" ").append(deleteBtn);
            $("<tr></tr>").append(checkBoxId)
                .append(empIdTd)
                .append(empNameTd)
                .append(genderTd)
                .append(emailTd)
                .append(deptNameTd)
                .append(btnTd)
                .appendTo("#emps_tables tbody");
        })
    }
    function build_page_info(data) {
        $("#page_info_area").empty();
        var pageInfo = data.extend.pageInfo;
        //当前记录数：当前 页，总 页，总 条记录
        $("#page_info_area").append("当前记录数：当前")
            .append(pageInfo.pageNum)
            .append("页，总")
            .append(pageInfo.pages)
            .append("页，总")
            .append(pageInfo.total)
            .append("条记录");
        totalRecord = pageInfo.total;
        currentPage = pageInfo.pageNum;
    }

    function to_page(pn) {
        $.ajax({
            url:"emps",
            data:"pn=" + pn,
            type:"get",
            success:function (data) {
                //console.log(data)
                build_emps_table(data);
                build_page_info(data);
                build_page_nav(data)
            }
        });
    }

    function build_page_nav(data) {
        $("#page_nav_area").empty();
        var ul = $("<ul></ul>").addClass("pagination");
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页"));
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));
        if(data.extend.pageInfo.hasPreviousPage == false){
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        }else{
            firstPageLi.click(function () {
                to_page(1)
            });
            prePageLi.click(function () {
                to_page(data.extend.pageInfo.pageNum - 1)
            });
        }
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页"));
        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
        if(data.extend.pageInfo.hasNextPage == false){
            lastPageLi.addClass("disabled");
            nextPageLi.addClass("disabled");
        }else {
            lastPageLi.click(function () {
                to_page(data.extend.pageInfo.pages)
            });
            nextPageLi.click(function () {
                to_page(data.extend.pageInfo.pageNum + 1)
            });
        }

        ul.append(firstPageLi).append(prePageLi);
        $.each(data.extend.pageInfo.navigatepageNums, function (index, item) {
            var numLi = $("<li></li>").append($("<a></a>").append(item).attr("href","#"));
            if(data.extend.pageInfo.pageNum == item){
                numLi.addClass("active")
            }
            numLi.click(function () {
                to_page(item)
            });
            ul.append(numLi);
        });
        ul.append(nextPageLi).append(lastPageLi);

        var navEle = $("<nav></nav>").append(ul);
        navEle.appendTo("#page_nav_area")
    }

    function reset_form(ele) {
        $(ele)[0].reset();
        $(ele).find("*").removeClass("has-success has-error");
        $(ele).find(".help-block").text("");
    }
    
    $("#emp_add_model_btn").click(function () {
        /*var $cr=$("#cr"); //jquery对象
var cr = $cr[0]; //dom对象 也可写成 var cr=$cr.get(0);
alert(cr.checked); //检测这个checkbox是否给选中

dom对象转换成jquery对象
对于一个dom对象，只需要用$()把dom对象包装起来，就可以获得一个jquery对象了，方法为$(dom对象);
复制代码 代码如下:

var cr=document.getElementById("cr"); //dom对象
var $cr = $(cr); //转换成jquery对象

转换后可以任意使用jquery中的方法了.*/
/*        $("#empAddModel form")[0].reset();*/
        reset_form("#empAddModel form");
        getDept("#dept_add_select");
        $("#empAddModel").modal({
            backdrop:"static"
        })
    });
    
    function getDept(ele) {
        $(ele).empty();
        $.ajax({
            url:"depts",
            type:"GET",
            success:function (data) {
               /* console.log(data)*/
               $.each(data.extend.depts,function (index, item) {
                   var optionEle = $("<option></option>").append(item.deptName).attr("value", item.deptId);
                   optionEle.appendTo(ele);
               })
            }
        })
    }
    function show_validate_msg(ele, status, msg) {
        $(ele).parent().removeClass("has-success has-error");
        $(ele).next("span").text("");
        if("success" == status){
            $(ele).parent().addClass("has-success");
            $(ele).next("span").text(msg);
        }
        else if("error" == status){
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg);
        }
    }
    
    function validate_add_form() {
        var empName = $("#empName_add_input").val();
        var regName = /(^[a-z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5}$)/;
        if(!regName.test(empName)){
            show_validate_msg("#empName_add_input", "error", "用户名可以是2-5位中文或者6-16位英文和数字的组合");
            //$("#empName_add_input").parent().addClass("has-error");
            //$("#empName_add_input").next("span").text("用户名可以是2-5位中文或者6-16位英文和数字的组合");
            return false;
        }else{
            back_check(empName);
            /*show_validate_msg("#empName_add_input", "success", "");*/
            /*$("#empName_add_input").parent().addClass("has-success");
            $("#empName_add_input").next("span").text("");*/
        }
        var email = $("#email_add_input").val();
        var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if(!regEmail.test(email)){
            show_validate_msg("#email_add_input", "error", "邮箱格式不正确");
/*            $("#email_add_input").parent().addClass("has-error");
            $("#email_add_input").next("span").text("邮箱格式不正确");*/
            return false;
        }else{
            show_validate_msg("#email_add_input", "success", "");
/*            $("#email_add_input").parent().addClass("has-success");
            $("#email_add_input").next("span").text("");*/
        }

       return true;
    }

    function back_check(empName) {
        $.ajax({
            url:"checkUser",
            data:"empName=" + empName,
            type:"POST",
            success:function (data) {
                if (data.code == 100){
                    show_validate_msg("#empName_add_input", "success", "用户名可用");
                    $("#emp_save_btn").attr("ajax-va", "success");
                }
                else {
                    show_validate_msg("#empName_add_input", "error",data.extend.va_msg);
                    $("#emp_save_btn").attr("ajax-va", "error");
                }
            }
        })
    }

    $("#empName_add_input").change(function () {
        var empName = this.value;
        back_check(empName);
    });

    $("#emp_save_btn").click(function () {
        if(!validate_add_form()){
            return false;
        }
/*        alert("  ");*/
/*        alert($("#empAddModel form").serialize());*/
        if($("#emp_save_btn").attr("ajax-va")=="error"){
            return false;
        }
        $.ajax({
            url:"emp",
            type:"POST",
            data:$("#empAddModel form").serialize(),
            success:function (data) {
                if(data.code == 100){
                    $('#empAddModel').modal('hide');
                    to_page(totalRecord);
                }
                else {
                    if (undefined != data.extend.errorFields.email){
                        show_validate_msg("#email_add_input", "error", data.extend.errorFields.email);
                    }
                    if (undefined != data.extend.errorFields.empName){
                        show_validate_msg("#empName_add_input", "error",data.extend.errorFields.empName);
                    }

                }

            }
        })
    })
    
    $(document).on("click", ".edit_btn",function () {
        getDept("#empUpdateModel select");
        getEmp($(this).attr("edit-id"));
        $("#emp_update_btn").attr("edit-id", $(this).attr("edit-id"));
        $("#empUpdateModel").modal({
            backdrop:"static"
        });
    });

    function getEmp(id) {
        $.ajax({
            url:"emp/"+ id,
            type:"GET",
            success:function (data) {
                //console.log(data);
                var empData = data.extend.emp;
                $("#empName_update_static").text(empData.empName);
                $("#email_update_input").val(empData.email);
                $("#empUpdateModel input[name=gender]").val([empData.gender]);
                $("#empUpdateModel select").val([empData.dId]);
            }
        });
    }
    
    $("#emp_update_btn").click(function () {
        //验证邮箱是否合法
        var email = $("#email_update_input").val();
        var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if(!regEmail.test(email)){
            show_validate_msg("#email_update_input", "error", "邮箱格式不正确");
            return false;
        }else{
            show_validate_msg("#email_update_input", "success", "");
        }

        //2.发送ajax请求保存更改
        $.ajax({
            url:"emp/" + $(this).attr("edit-id"),
            type:"PUT",
            data:$("#empUpdateModel form").serialize(),
            success:function (data) {
                $("#empUpdateModel").modal("hide");
                //alert(data.msg);
                to_page(currentPage);
            }

        })

    })

    $(document).on("click", ".delete_btn",function () {
       var empName = $(this).parents("tr").find("td:eq(2)").text();
       if(confirm("确认删除【" + empName +"】吗？")){
           $.ajax({
               url:"emp/" + $(this).attr("delete-id"),
               type:"DELETE",
               success:function (data) {
                   alert(data.msg);
                   to_page(currentPage);
               }
           })
       }
    });

    //完成全选，全不选
    $("#check_all").click(function () {
        //dom原生的属性，需要用prop来获取。对于自定义的属性，可以用attr来获取
        //alert($(this).prop("checked"));
        $(".check_item").prop("checked",$(this).prop("checked"));
    })

    $(document).on("click", ".check_item",function () {
        var flag = $(".check_item:checked").length == $(".check_item").length;
        $("#check_all").prop("checked", flag);
    })

    //点击全部删除，就批量删除
    $("#emp_del_all_btn").click(function () {
        var empNames = "";
        var del_idstr = "";
        $.each($(".check_item:checked"),function () {
            empNames += $(this).parents("tr").find("td:eq(2)").text() + ", ";
            del_idstr += $(this).parents("tr").find("td:eq(1)").text() + "-";
            /*alert($(this).parents("tr").find("td:eq(2)").text());*/
        });
        empNames = empNames.substring(0, empNames.length - 2);
        del_idstr = del_idstr.substring(0, del_idstr.length - 1);
        if(confirm("确认删除【" + empNames + "】吗？")){
            $.ajax({
                url:"emp/" + del_idstr,
                type:"DELETE",
                success:function (data) {
                    alert(data.msg);
                    to_page(currentPage);
                }
            })
        }
    })
</script>
</body>
</html>
